package labox.innovation.gameserver.network.clientpackets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.TradeList;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;

/**
 * 交易完成 或 结束
 * 客户端请求
 * @author zjj
 *
 */
public final class TradeDone extends L2GameClientPacket {
	private static final String _C__77_TRADEDONE = "[C] 0x77 TradeDone";

	private static final Logger _log = LoggerFactory.getLogger(TradeDone.class.getName());

	private static final int CONFIRM_TRADE = 1;

	private int _response; //1:确认交易  0取消交易

	@Override
	protected void readImpl() {
		_response = readByte();
	}

	@Override
	protected void runImpl() {
		FuzePcInstance player = getClient().getActiveChar();
		if (player == null)
			return;
		TradeList trade = player.getActiveTradeList();
		if (trade == null) {
			if (_log.isDebugEnabled()) {
				_log.warn("player.getTradeList == null in " + getType() + " for player " + player.getName(), Config.SERVER_ID);
			}
			return;
		}

		//确认交易
		if (_response == CONFIRM_TRADE) {
			//确认交易时 没有被锁定 那么返回
			if (!trade.isLocked())
				return;

			if (trade.getPartner() == null || player.getKnownList().getKnownCharacters().get(trade.getPartner().getObjectId()) == null) {
				// Trade partner not found, cancel trade
				player.cancelActiveTrade();
				SystemMessage msg = new SystemMessage(SystemMessageId.TARGET_IS_NOT_FOUND_IN_THE_GAME);
				player.sendPacket(msg);
				msg = null;
				return;
			}

			if (!player.getAccessLevel().allowTransaction()) {
				player.cancelActiveTrade();
				player.sendMessage("Transactions are disable for your Access Level");
				return;
			}

			if (player.getInstanceId() != trade.getPartner().getInstanceId() && player.getInstanceId() != -1) {
				player.cancelActiveTrade();
				return;
			}

			trade.confirm();
		} else
			player.cancelActiveTrade();
	}

	/* (non-Javadoc)
	 * @see labox.innovation.gameserver.clientpackets.ClientBasePacket#getType()
	 */
	@Override
	public String getType() {
		return _C__77_TRADEDONE;
	}
}
